﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using BestTrader.Cms.Admin.Models;
using BestTrader.Cms.Admin.Filter;
using BestTrader.Cms.Core.Helper;
using BestTrader.Cms.IServices;
using System.Security.Claims;
using BestTrader.Cms.ViewModels;
using BestTrader.Cms.Admin.Validation;
using FluentValidation.Results;
using Microsoft.AspNetCore.Authorization;

namespace BestTrader.Cms.Admin.Controllers
{
    /// <summary>
    /// 手续费(服务费)设置
    /// </summary>
    [Authorize]
    public class ServiceChargeController : BaseController
    {
        public String UserId { get { return User.Claims.FirstOrDefault(x => x.Type == "UserId")?.Value; } }
        public String RoleId { get { return User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Role)?.Value; } }
        private readonly IServiceChargeService _service;
        private readonly ICacheService _cacheService;
        public ServiceChargeController(IServiceChargeService service, ICacheService cacheService) {
            this._service = service;
            this._cacheService = cacheService;
        }

        /// <summary>
        /// 主界面
        /// </summary>
        public IActionResult Index() => View();

        public string LoadData([FromQuery]ServiceChargeRequestModel model)
        {
            var user = User.Claims.FirstOrDefault(x => x.Type == "UserId")?.Value;
            var role = User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Role)?.Value;
            return JsonHelper.ObjectToJSON(_service.LoadData(model, user, role));
        }

        [HttpGet]
        public IActionResult AddOrModify()
        {
            ViewData["ProjectTypes"] = _cacheService.GetCacheProjectTypes();

            return View();
        }

        [HttpGet]
        public string GetHistoryByManagerId([FromQuery]ServiceChargeHistoryQueryModel item)
        {
            var result = _service.GetHistoryByManagerId(item);

            return JsonHelper.ObjectToJSON(result);
        }
        

        [HttpPost, ValidateAntiForgeryToken]
        public string AddOrModify([FromForm]ServiceChargeAddOrModifyModel item)
        {
            var result = new BaseResult();
            ServiceChargeValidation validationRules = new ServiceChargeValidation();
            ValidationResult results = validationRules.Validate(item);
            if (results.IsValid)
            {
                var userId = User.Claims.FirstOrDefault(x => x.Type == "UserId")?.Value;
                result = _service.AddOrModify(item, userId);
            }
            else
            {
                result.ResultCode = ResultCodeAddMsgKeys.CommonModelStateInvalidCode;
                result.ResultMsg = results.ToString("||");
            }
            return JsonHelper.ObjectToJSON(result);
        }
    }
}
